<template>
  <div class="reservations">
    <h2>Reservation History</h2>
    <div v-if="reservations.length">
      <table>
        <thead>
        <tr>
          <th>订单编号</th>
          <th>借出门店</th>
          <th>归还门店</th>
          <th>日期</th>
          <th>订单状态</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="reservation in reservations" :key="reservation.reservationID">
          <td>{{ reservation.reservationID }}</td>
          <td>{{ reservation.expectedCheckoutStoreID }}</td>
          <td>{{ reservation.expectedCheckoutStoreID }}</td>
          <td>{{ reservation.expectedCheckoutTime }} to {{ reservation.expectedReturnTime }}</td>
          <td>{{ reservation.reservationStatus }}</td>
          <td>
            <el-button v-if="reservation.reservationStatus === '借出'" @click="openRenewForm(reservation)" type="primary" size="default">Renew</el-button>
            <el-button v-if="reservation.reservationStatus === '未借出'" @click="cancelReservation(reservation)" type="danger" size="default">Cancel</el-button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <div v-else>
      <p>没有订单</p>
    </div>

    <!-- Renewal Form Dialog -->
    <el-dialog v-model="dialogVisible" title="Renewal Form" width="500px">
      <el-form label-width="auto" style="max-width: 1200px">
        <el-form-item label="Return To">
          <Select v-model="renewForm.returnTo" @update:selectedStore="handleSelectedStore2"></Select>
        </el-form-item>
        <el-form-item label="Return Time">
          <el-date-picker
              v-model="renewForm.returnTime"
              type="datetime"
              placeholder="Select date and time">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitRenewal">Submit</el-button>
      </span>
    </el-dialog>


  <el-dialog :v-model="errorDialogVisible" title="Error">
    <span>{{ errorMessage }}</span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="errorDialogVisible = false">OK</el-button>
      </span>
  </el-dialog>

  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue';
import { useStore } from 'vuex';
import axios from 'axios';
import Select from "@/components/Select.vue";
import router from '../router';
import { ElDialog, ElForm, ElFormItem, ElButton, ElDatePicker } from 'element-plus';

const store = useStore();
const reservations = ref([]);
const dialogVisible = ref(false);
const errorDialogVisible = ref(false);
const errorMessage = ref('');

const renewForm = reactive({
  returnTo: '',
  returnTime: '',
  reservationID: '',
  userID: ''
});

onMounted(() => {
  fetchReservations();
});

const fetchReservations = async () => {
  const token = store.getters['auth/getToken'];
  if (!token) {
    logout();
    return;
  }
  try {
    const response = await axios.get('/api/Reservation', {
      headers: {
        'token': token
      }
    });
    if (response.data.statusCode === 200) {
      reservations.value = response.data.data;
    } else {
      console.error('Error fetching reservations:', response.data.message);
      if (response.data.statusCode === 401) {
        logout();
      }
    }
  } catch (error) {
    if (error.response && error.response.statusCode === 401) {
      logout();
    } else {
      console.error('Error fetching reservations:', error);
    }
  }
};

const logout = () => {
  store.dispatch('auth/logout');
  router.push('/login');
};

const openRenewForm = (reservation) => {
  renewForm.returnTo = reservation.expectedReturnStoreID;
  renewForm.returnTime = reservation.expectedReturnTime;
  renewForm.reservationID = reservation.reservationID;
  renewForm.userID = reservation.userID;
  dialogVisible.value = true;
};

const submitRenewal = async () => {
  const token = store.getters['auth/getToken'];
  try {
    const response = await axios.post('/api/Reservation/Renew', renewForm, {
      headers: {
        'Content-Type': 'application/json',
        'token': token
      }
    });
    if (response.data.statusCode === 200) {
      fetchReservations();
      dialogVisible.value = false;
    }
    else if(response.data.statusCode === 414) {
      console.error('Error renewing reservation:', response.data.message);
      errorMessage.value = `续借失败：只有状态为借出的订单可以续借`;
      errorDialogVisible.value = true;
    }
    else {
      console.error('Error renewing reservation:', response.data.message);
      errorMessage.value = `${response.data.message}`;
      errorDialogVisible.value = true;
    }
  } catch (error) {
    console.error('Error renewing reservation:', error);
    errorMessage.value = ` ${error.message}`;
    errorDialogVisible.value = true;
  }
};

const cancelReservation = async (reservation) => {
  const token = store.getters['auth/getToken'];
  try {
    const response = await axios.delete(`/api/Reservation/${reservation.reservationID}`, {
      headers: {
        'token': token
      }
    });
    if (response.data.statusCode === 200) {
      fetchReservations();
    } else {
      console.error('Error cancelling reservation:', response.data.message);
      errorMessage.value = `${response.data.message}`;
      errorDialogVisible.value = true;
    }
  } catch (error) {
    console.error('Error cancelling reservation:', error);
  }
};

const handleSelectedStore2 = (storeId) => {
  renewForm.returnTo = storeId;
};
</script>

<style scoped>
.reservations {
  padding: 20px;
}

.reservations h2 {
  color: #333;
}

.reservations table {
  width: 100%;
  border-collapse: collapse;
}

.reservations th,
.reservations td {
  padding: 8px 12px;
  border: 1px solid #ddd;
}

.reservations th {
  background-color: #f5f5f5;
}
</style>
